package zclTool;

import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import xml.*;
/*
 * 
 * This class demonstrates how to interact with Googles Spell Checker. Google uses 
 * this spell checker through their browser toolbar. Therefore this class just mimics
 * the toolbar. This is not an official API. We are not liable for anything if Google
 * comes after you. 
 * 
 * More information at http://www.gmacker.com
 *
 */

public class GSpellCheck {
	
	
	/*
	 * This method makes a call to the Google Spell Checker and 
	 * returns possible corrections.
	 * 
	 * @param pText - any text that needs to be spell checked
	 *      
	 */
	public static String[] doSpellCheck(String pText) {
		try {
			//Format the XML that needs to be send to Google Spell Checker.
			StringBuffer requestXML = new StringBuffer();
			requestXML.append("<spellrequest textalreadyclipped=\"0\" ignoredups=\"1\" ignoredigits=\"1\" ignoreallcaps=\"0\"><text>");
			requestXML.append(pText);
			requestXML.append("</text></spellrequest>");
			
			//The Google Spell Checker URL
			URL url = new URL("https://www.google.com/tbproxy/spell?lang=en&hl=en");
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);

			OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
			out.write(requestXML.toString());
			out.close();

			//Get the result from Google Spell Checker
			InputStream in = conn.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String inputLine;
			StringBuffer sb = new StringBuffer();
			while ((inputLine = br.readLine()) != null) {
				//Print out the response from Google
				//System.out.println(inputLine); 
				sb.append(inputLine);
			}
			in.close();
			
			String a = sb.toString().replaceAll("\\<.*?\\>", "");
			String []b = a.split("\t");
			return b;
		}
		catch (Exception e) {
			System.out.println("Exception "+ e);
		}
		return null;
	}
	
	/*
	 * Main method that tries to get hello world back from Google Spell checker
	 * 
	 */
	public static void main(String[] args)
	{
		String []a = GSpellCheck.doSpellCheck("lastmajorleague");
		System.out.println(a[0]);
	}

}
